package basics.iconcurrent.lock;

import java.time.Duration;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author or2
 * @Description 锁的公平与否 - 线程唤醒带来的开销对比
 * @create 2021年09月13日 时间: 17:19
 */
public class FairOrNot {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

//        ReentrantLock reentrantLock = new ReentrantLock(false);
        ReentrantLock reentrantLock = new ReentrantLock(true);
        ThreadPoolExecutor threadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(3);
        AtomicInteger atomicInteger = new AtomicInteger();

        Callable<Void> task = () -> {
            int increment = atomicInteger.getAndIncrement();
            reentrantLock.lock();
            System.out.println(Thread.currentThread().getName() + " - " + increment);
            reentrantLock.unlock();
//            两次任务
            reentrantLock.lock();
            System.out.println(Thread.currentThread().getName() + " - " + increment);
            reentrantLock.unlock();
            return null;
        };

        int times = 100000;
        Future[] futures = new Future[times];
        long start = System.currentTimeMillis();
        for (int i = 0; i < times; i++) {
            futures[i] = threadPool.submit(task);
        }
        for (int i = 0; i < futures.length; i++) {
            futures[i].get();
        }
        long end = System.currentTimeMillis();
        threadPool.shutdown();
        System.out.println(Duration.ofMillis(end - start));
    }
}
